package com.transaction;

import org.apache.ibatis.transaction.Transaction;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 把由 {@link PlatformTransactionManager}管理的事务
 * 适配到 Mybatis 框架中
 */
public class SpringTransactionStatusAdaptor implements Transaction {

    private final PlatformTransactionManager transactionManager;

    private final TransactionStatus transactionStatus;

    private final DataSource dataSource;

    private final int timeout;

    public SpringTransactionStatusAdaptor(PlatformTransactionManager transactionManager, TransactionStatus transactionStatus, DataSource dataSource, int timeout) {
        this.transactionManager = transactionManager;
        this.dataSource = dataSource;
        this.transactionStatus = transactionStatus;
        this.timeout = timeout;
    }

    @Override
    public Connection getConnection() throws SQLException {

        return DataSourceUtils.getConnection(dataSource);
    }

    @Override
    public void commit() throws SQLException {
        transactionManager.commit(transactionStatus);
    }

    @Override
    public void rollback() throws SQLException {

        /*
        transactionStatus.setRollbackOnly();
        transactionManager.commit(transactionStatus);
        最终也会调用 transactionManager.doRollback() 方法

        但是下面的写法更清晰和直观
        */
        transactionManager.rollback(transactionStatus);
    }

    @Override
    public void close() throws SQLException {

    }

    @Override
    public Integer getTimeout() throws SQLException {
        return timeout;
    }
}
